package cn.com.analyze;

import java.util.List;

import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.format.FormatUtils;
import org.jnetpcap.protocol.network.Ip4;

import cn.com.tool.Nettool;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class TotalBytes {
	private List<JPacket> packets;
	int total;
	int total_send;
	int total_recv;
	final int COOKED_HEAD_LEN = 16;
	
	Context c;
	
	public TotalBytes(Context context)
	{
		c = context;
		
		SharedPreferences mSharedPreferences = c.getSharedPreferences("hostip", Activity.MODE_PRIVATE);
		hostip = mSharedPreferences.getString("hostip", "");
	}
	public TotalBytes(Context context, List<JPacket> lst)
	{
		c = context;
		packets = lst;
		total = 0;
		total_send = 0;
		total_recv = 0;
		
		SharedPreferences mSharedPreferences = c.getSharedPreferences("hostip", Activity.MODE_PRIVATE);
		hostip = mSharedPreferences.getString("hostip", "");
	}
	
	Ip4 ip4 = new Ip4();
	String src = null;
	String dst = null;
	String hostip = null;
	public void calculate()
	{
		for(JPacket packet : packets)
		{
			if(packet.hasHeader(Ip4.ID))
			{
				packet.getHeader(ip4);
				src = FormatUtils.ip(ip4.source());
				dst = FormatUtils.ip(ip4.destination());
				if(src.equals(hostip))
					total_send += packet.size() - COOKED_HEAD_LEN;
				else if(dst.equals(hostip))
					total_recv += packet.size() - COOKED_HEAD_LEN;
			}	
		}
	}
	
	public void add(JPacket packet)
	{
		//Log.e("TotalBytes-add", "time stamp is " + 
		//                packet.getCaptureHeader().seconds() + "." + 
		//                packet.getCaptureHeader().nanos());
		if(packet.hasHeader(Ip4.ID))
		{
			packet.getHeader(ip4);
			src = FormatUtils.ip(ip4.source());
			dst = FormatUtils.ip(ip4.destination());
			//Log.i("TotalBytes-add", "---------------read a ipv4 packet--------------" + "src is " + src + " " + "dst is " + dst);
//			Log.i("TotalBytes-add", "hostip is " + hostip);
			if(src.equals(hostip))
				total_send += packet.size() - COOKED_HEAD_LEN;
			else if(dst.equals(hostip))
				total_recv += packet.size() - COOKED_HEAD_LEN;
		}	
	}
	
	public int getTotalSend()
	{
		return total_send;
	}
	public int getTotalRecv()
	{
		return total_recv;
	}
	public int getTotalBytes()
	{
		total = total_send + total_recv;
		return total;
	}

}
